import axios from 'axios'
import {
  Message
} from 'iview'
import store from '@/store'
const addErrorLog = errorInfo => {
  const {
    statusText,
    status,
    request: {
      responseURL
    },
    config: {
      data
    }
  } = errorInfo
  console.log(`请求地址：${responseURL} 请求参数：${data}`)
  console.log(`错误码：${status} ${statusText} `)
  addError(errorInfo.data)
}

const addError = errorInfo => {
  let content
  if (typeof errorInfo === 'string') content = '请求异常,联系管理员'
  else content = `异常代码：${errorInfo.code},\n异常信息：${errorInfo.message}`
  Message.error({ content })
}
class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json'
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const {
        data
      } = res
      if (data.code === 200) {
        return data.data
      } else if (data.code === 403) {
        store.dispatch('handleLogOut')
      } else {
        addError(data)
        return Promise.reject(data)
      }
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const {
          request: {
            statusText,
            status
          },
          config
        } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: {
            responseURL: config.url
          }
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
